package com.joven.interface2.service.impl;


import com.alibaba.fastjson.JSON;
import com.joven.core.constant.Status;
import com.joven.core.model.Person;
import com.joven.interface2.constant.JovenOutput;
import com.joven.interface2.mapper.PersonMapper;
import com.joven.interface2.service.RocketMqService;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * @author joven_wong
 * 2021/6/10 15:03
 */
@Service
public class RocketMqServiceImpl implements RocketMqService {

//    @Autowired
//    RocketMQTemplate rocketMQTemplate;

    @Autowired
    JovenOutput jovenOutput;

    /**
     *  这里消息发送只是prepare发送，
     *  后面消息队列中prepare成功后，在TestTransactionListener中的executeLocalTransaction的方法中决定是否要提交本地事务
     * @return code
     */
    @Override
    public String testTransaction() {
        Person p1 = Person.builder().name("TPan").age(23).build();

        // 事务id
        String transactionId = "trans-1";
        //rocketMQTemplate 发送消息
//        rocketMQTemplate.sendMessageInTransaction("yu", "test-score",
//                MessageBuilder.withPayload(p1)
//                        .setHeader(RocketMQHeaders.TRANSACTION_ID, transactionId)
//                        .setHeader("share_id", 3).build()
//                ,4L);

        String qjID = String.valueOf(new Random().nextInt());
        //通过 JovenOutput 获得 MessageChannel 对象，然后发送消息。
        boolean b= jovenOutput.output().send(
                MessageBuilder.withPayload(JSON.toJSONString(p1))
                .setHeader(RocketMQHeaders.TRANSACTION_ID, transactionId)
                .setHeader("args", qjID).build());
        String i = Status.FAIL.getCode();
        if(b){
            i = Status.SUCCESS.getCode();
            System.out.println(" prepare 消息发送成功");
        }
        return i;
    }
}
